import unittest
import sys
# import HTMLTestRunner

sys.path.append("..")
import ascend
import numpy as np
import cv2
import pdb

class ImageTest(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        print("setUpClass: executed before all testcase.")

    @classmethod
    def tearDownClass(self):
        print("tearDownClass: executed after all testcase.")

    def setUp(self):
        print("execute setUp\n")

    def tearDown(self):
        print("execute tearDown")

    def assertTrue(self, expr, msg=None):
        print('[FAIL] %s' % msg if not expr else '[SUCCESS]')
        super(ImageTest, self).assertTrue(expr, msg)
    
    # all testcase write below:
    def test_imdecode_001(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)

        data = np.fromfile('./image/girl1.jpg', dtype=np.uint8)
        image = Img.imdecode(data)
        img_color = cv2.cvtColor(image.to_np, cv2.COLOR_YUV2RGB_NV21)

        cv2.imshow('result', img_color)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

        self.assertTrue(img_color is not None, msg="test ok")
    
    def test_imresize_002(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)

        yuv = Img.imread('./image/girl1.jpg', keep_shape=True)

        yuv_resized = Img.imresize(yuv, (320, 540))
        img_color = cv2.cvtColor(yuv_resized.to_np, cv2.COLOR_YUV2RGB_NV21)

        cv2.imshow('result', img_color)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
  
        self.assertTrue(img_color is not None, msg="test ok")

    # this testcase has problem
    def test_imrescale_003(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)

        yuv = Img.imread('./image/girl1.jpg', keep_shape=True)

        yuv_rescale = Img.imrescale(yuv, 0.3)
        img_color = cv2.cvtColor(yuv_rescale.to_np, cv2.COLOR_YUV2RGB_NV21)
        cv2.imshow('result', img_color)
        cv2.waitKey(0)

        yuv_resized = Img.imrescale(yuv, (320, 540))
        img_color = cv2.cvtColor(yuv_resized.to_np, cv2.COLOR_YUV2RGB_NV21)
        cv2.imshow('result', img_color)
        cv2.waitKey(0)

        cv2.destroyAllWindows()
        self.assertTrue(img_color is not None, msg="test ok")

    def test_imcrop_004(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)

        yuv = Img.imread('./image/girl1.jpg', keep_shape=True)

        bboxes = np.array([[20, 40, 159, 259],[400, 200, 479, 419]], dtype=int)
        yuv_croped = Img.imcrop(yuv, bboxes)
        for _, yuv in enumerate(yuv_croped):
            img_color = cv2.cvtColor(yuv.to_np, cv2.COLOR_YUV2RGB_NV21)
            cv2.imshow('result', img_color)
            cv2.waitKey(0)

        cv2.destroyAllWindows()
        self.assertTrue(img_color is not None, msg="test ok")
    
    def test_imcrop_005(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)
        
        yuv = Img.imread('./image/img.jpg')

        bboxes = np.array([400, 200, 479, 419], dtype=int)
        yuv_croped = Img.imcrop(yuv, bboxes, scale=0.5)
        for _, yuv in enumerate(yuv_croped):
            img_color = cv2.cvtColor(yuv.to_np, cv2.COLOR_YUV2RGB_NV21)
            cv2.imshow('result', img_color)
            cv2.waitKey(0)

        cv2.destroyAllWindows()
        self.assertTrue(img_color is not None, msg="test ok")

    
    def test_bbox_resize_006(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)

        yuv = Img.imread('./image/img.jpg')

        bboxes = np.array([[20, 40, 159, 259],[400, 200, 479, 419]], dtype=int)
        # bboxes = np.array([400, 200, 479, 419], dtype=int)
        sizes = np.array([[300, 300], [400, 400]])
        # sizes = np.array([400, 400])
        yuv_croped = Img.bbox_resize(yuv, bboxes, sizes)
        for i, yuv in enumerate(yuv_croped):
            img_color = cv2.cvtColor(yuv.to_np, cv2.COLOR_YUV2RGB_NV21)
            cv2.imshow('result', img_color)
            cv2.waitKey(0)

        cv2.destroyAllWindows()
        self.assertTrue(img_color is not None, msg="test ok")
    
    
    def test_impad_007(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)
        
        yuv = Img.imread('./image/img.jpg', keep_shape=True)

        yuv_resized = Img.imresize(yuv, (416, 236))
        img_color = cv2.cvtColor(yuv_resized.to_np, cv2.COLOR_YUV2RGB_NV21)
        cv2.imshow('result', img_color)
        cv2.waitKey()

        yuv_pad = Img.impad(yuv_resized, shape=(416, 416))
        img_color = cv2.cvtColor(yuv_pad.to_np, cv2.COLOR_YUV2RGB_NV21)
        cv2.imshow('result', img_color)
        cv2.waitKey()

        cv2.destroyAllWindows()
        self.assertTrue(img_color is not None, msg="test ok")
    
    def test_impad_008(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)
        
        yuv = Img.imread('./image/img.jpg', keep_shape=True)

        yuv_resized = Img.imrescale(yuv, (416, 416))
        # img_color = cv2.cvtColor(yuv_resized.to_np, cv2.COLOR_YUV2RGB_NV21)
        # cv2.imshow('result1', img_color)
        # cv2.waitKey()

        yuv_pad = Img.impad(yuv_resized, padding=(20, 50, 100, 200), pad_val=128)
        yuv_pad_np = yuv_pad.to_np
        img_color2 = cv2.cvtColor(yuv_pad_np, cv2.COLOR_YUV2RGB_NV21)
        cv2.imshow('result2', img_color2)
        cv2.waitKey()

        cv2.destroyAllWindows()
        self.assertTrue(img_color2 is not None, msg="test ok")
    
    def test_imcrop_paste_009(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)
        
        yuv_src = Img.imread('./image/img.jpg')
        yuv_dst = Img.imread('./image/xiaoxin.jpg')


        # crop_bbox = np.array([40, 30, 140, 230], dtype='int32')
        # paste_bbox = np.array([70, 80, 170, 280], dtype='int32')
        crop_bbox = np.array([50, 240, 340, 630], dtype='int32')
        paste_bbox = np.array([170, 280, 470, 680], dtype='int32')
        Img.imcrop_paste(yuv_src, yuv_dst, crop_bbox, paste_bbox)
        img_color = cv2.cvtColor(yuv_dst.to_np, cv2.COLOR_YUV2RGB_NV21)
        cv2.imshow('result1', img_color)
        cv2.waitKey()

        crop_bbox = np.array([[132, 264, 300, 480], [400, 320, 620, 587]], dtype='int32')
        paste_bbox = np.array([[480, 73, 693, 340], [346, 420, 538, 740]], dtype='int32')
        Img.imcrop_paste(yuv_src, yuv_dst, crop_bbox, paste_bbox)
        img_color = cv2.cvtColor(yuv_dst.to_np, cv2.COLOR_YUV2RGB_NV21)
        cv2.imshow('result2', img_color)
        cv2.waitKey()

        cv2.destroyAllWindows()
        self.assertTrue(img_color is not None, msg="test ok")
    
    def test_imread_010(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)

        yuv = Img.imread('./image/girl1.jpg', keep_shape=True)
        img_color = cv2.cvtColor(yuv.to_np, cv2.COLOR_YUV2RGB_NV21)
        cv2.imshow('yuv', img_color)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    def test_imencode_011(self):
        pdb.set_trace()
        ctx = ascend.Context({12}).context_dict[12]
        Img = ascend.Image(ctx)

        yuv = Img.imread('./image/girl1.jpg')

        img_encode = Img.imencode('.jpg', yuv)
        data_encode = np.array(img_encode).tostring()

        with open('img_encode.jpg', 'wb') as f:
            f.write(data_encode)
            f.flush
            

if __name__ == '__main__':
        #####################################
        # 1.test single case
        # ImageTest is the object name, test_TS_001 is the case name
        suite = unittest.TestSuite()
        # suite.addTest(ImageTest("test_imdecode_001"))
        # suite.addTest(ImageTest("test_imresize_002"))
        # suite.addTest(ImageTest("test_imrescale_003"))
        # suite.addTest(ImageTest("test_imcrop_004"))
        # suite.addTest(ImageTest("test_imcrop_005"))
        # suite.addTest(ImageTest("test_bbox_resize_006"))
        # suite.addTest(ImageTest("test_impad_007"))
        # suite.addTest(ImageTest("test_impad_008"))
        suite.addTest(ImageTest("test_imcrop_paste_009"))
        # suite.addTest(ImageTest('test_imread_010'))
        runner = unittest.TextTestRunner().run(suite)

        # save the test result to html
        # filename = './apptestresult.html'
        # fb = open(filename, 'wb')
        # runner = HTMLTestRunner.HTMLTestRunner(stream=fb, title="测试HTMLTestRunner", description="测试HTMLTestRunner")
        # runner.run(suite)
        # fb.close()

        ######################################
        # 2. test all case
        # unittest.main(testRunner=unittest.TextTestRunner(stream=None, verbosity=2))

